<template>
  <Dialog v-model="dialogVisible" title="异议处理" width="1000px">
    <el-form
      ref="formRef"
      :model="handleForm"
      :rules="handleRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 异议信息 -->
      <el-divider content-position="left">异议信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="异议编号">
          {{ objectionData.objectionNo || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="申请人">
          {{ objectionData.applicantName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ objectionData.phone || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">
          {{ objectionData.applyTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="异议类型">
          <el-tag>{{ getObjectionTypeName(objectionData.objectionType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusColor(objectionData.status)">
            {{ getStatusName(objectionData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="异议内容" :span="2">
          <div style="white-space: pre-wrap; max-height: 100px; overflow-y: auto;">
            {{ objectionData.objectionContent || '-' }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 相关材料 -->
      <el-divider content-position="left" v-if="objectionData.attachments && objectionData.attachments.length > 0">
        相关材料
      </el-divider>
      <div v-if="objectionData.attachments && objectionData.attachments.length > 0" style="margin-bottom: 20px;">
        <el-tag 
          v-for="(file, index) in objectionData.attachments" 
          :key="index"
          style="margin-right: 10px; margin-bottom: 5px;"
          @click="previewFile(file)"
        >
          <el-icon><Paperclip /></el-icon>
          {{ file.fileName }}
        </el-tag>
      </div>
      
      <!-- 处理表单 -->
      <el-divider content-position="left">处理结果</el-divider>
      <el-form-item label="处理结果" prop="handleResult">
        <el-radio-group v-model="handleForm.handleResult">
          <el-radio :value="1">异议成立</el-radio>
          <el-radio :value="2">异议不成立</el-radio>
          <el-radio :value="3">部分成立</el-radio>
          <el-radio :value="4">需要进一步调查</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item 
        label="处理措施" 
        prop="handleMeasures" 
        v-if="handleForm.handleResult === 1 || handleForm.handleResult === 3"
      >
        <el-checkbox-group v-model="handleForm.handleMeasures">
          <el-checkbox label="reScore">重新评分</el-checkbox>
          <el-checkbox label="reExam">重新考试</el-checkbox>
          <el-checkbox label="changeResult">更改评价结果</el-checkbox>
          <el-checkbox label="compensation">给予补偿</el-checkbox>
          <el-checkbox label="apology">公开道歉</el-checkbox>
          <el-checkbox label="other">其他措施</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item 
        label="不成立原因" 
        prop="rejectReasons" 
        v-if="handleForm.handleResult === 2"
      >
        <el-checkbox-group v-model="handleForm.rejectReasons">
          <el-checkbox label="insufficient">证据不足</el-checkbox>
          <el-checkbox label="invalid">异议无效</el-checkbox>
          <el-checkbox label="timeout">超出时限</el-checkbox>
          <el-checkbox label="duplicate">重复申请</el-checkbox>
          <el-checkbox label="frivolous">恶意申请</el-checkbox>
          <el-checkbox label="other">其他原因</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="处理说明" prop="handleDescription">
        <el-input
          v-model="handleForm.handleDescription"
          type="textarea"
          :rows="4"
          placeholder="请详细说明处理过程和依据"
        />
      </el-form-item>
      
      <el-form-item label="处理时限" prop="handleDeadline" v-if="handleForm.handleResult === 4">
        <el-date-picker
          v-model="handleForm.handleDeadline"
          type="datetime"
          placeholder="选择处理时限"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      
      <el-form-item label="处理人员" prop="handler">
        <el-input v-model="handleForm.handler" placeholder="处理人员" readonly />
      </el-form-item>
      
      <el-form-item label="复核人员" prop="reviewer">
        <el-select v-model="handleForm.reviewer" placeholder="请选择复核人员">
          <el-option label="李主任" value="reviewer1" />
          <el-option label="王科长" value="reviewer2" />
          <el-option label="张处长" value="reviewer3" />
        </el-select>
      </el-form-item>
      
      <!-- 处理结果通知 -->
      <el-form-item label="通知方式" prop="notifyMethods">
        <el-checkbox-group v-model="handleForm.notifyMethods">
          <el-checkbox label="phone">电话通知</el-checkbox>
          <el-checkbox label="sms">短信通知</el-checkbox>
          <el-checkbox label="email">邮件通知</el-checkbox>
          <el-checkbox label="mail">邮寄通知</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    
    <!-- 处理历史 -->
    <el-divider content-position="left" v-if="handleHistory.length > 0">
      处理历史
    </el-divider>
    <el-timeline v-if="handleHistory.length > 0">
      <el-timeline-item
        v-for="(record, index) in handleHistory"
        :key="index"
        :timestamp="record.handleTime"
        :type="getHistoryType(record.handleResult)"
      >
        <el-card>
          <h4>{{ getHandleResultName(record.handleResult) }}</h4>
          <p><strong>处理人：</strong>{{ record.handler }}</p>
          <p v-if="record.handleDescription"><strong>处理说明：</strong>{{ record.handleDescription }}</p>
          <p v-if="record.handleMeasures && record.handleMeasures.length > 0">
            <strong>处理措施：</strong>{{ formatMeasures(record.handleMeasures) }}
          </p>
        </el-card>
      </el-timeline-item>
    </el-timeline>
    
    <template #footer>
      <el-button @click="submitHandle" type="primary" :loading="formLoading">提交处理</el-button>
      <el-button @click="saveAsDraft" type="info">保存草稿</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Paperclip } from '@element-plus/icons-vue'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()

const objectionData = ref({} as any)
const handleForm = ref({
  objectionId: '',
  handleResult: undefined,
  handleMeasures: [] as string[],
  rejectReasons: [] as string[],
  handleDescription: '',
  handleDeadline: '',
  handler: '当前用户',
  reviewer: '',
  notifyMethods: [] as string[]
})

const handleRules = ref({
  handleResult: [{ required: true, message: '请选择处理结果', trigger: 'change' }],
  handleMeasures: [
    { 
      validator: (rule: any, value: string[], callback: Function) => {
        if ((handleForm.value.handleResult === 1 || handleForm.value.handleResult === 3) && (!value || value.length === 0)) {
          callback(new Error('请选择处理措施'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  rejectReasons: [
    { 
      validator: (rule: any, value: string[], callback: Function) => {
        if (handleForm.value.handleResult === 2 && (!value || value.length === 0)) {
          callback(new Error('请选择不成立原因'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  handleDescription: [{ required: true, message: '处理说明不能为空', trigger: 'blur' }],
  reviewer: [{ required: true, message: '请选择复核人员', trigger: 'change' }],
  notifyMethods: [{ required: true, message: '请至少选择一种通知方式', trigger: 'change' }]
})

// 处理历史
const handleHistory = ref([
  {
    handleTime: '2023-12-01 14:00:00',
    handleResult: 4,
    handler: '张处理员',
    handleDescription: '已受理异议申请，正在调查中',
    handleMeasures: []
  }
])

const getObjectionTypeName = (type: number) => {
  const typeMap = { 1: '成绩异议', 2: '程序异议', 3: '结果异议', 4: '其他异议' }
  return typeMap[type] || '-'
}

const getStatusName = (status: number) => {
  const statusMap = { 1: '待处理', 2: '处理中', 3: '已处理', 4: '已关闭' }
  return statusMap[status] || '-'
}

const getStatusColor = (status: number) => {
  const colorMap = { 1: 'warning', 2: 'primary', 3: 'success', 4: 'info' }
  return colorMap[status] || 'info'
}

const getHandleResultName = (result: number) => {
  const resultMap = { 1: '异议成立', 2: '异议不成立', 3: '部分成立', 4: '调查中' }
  return resultMap[result] || '-'
}

const getHistoryType = (result: number) => {
  const typeMap = { 1: 'success', 2: 'danger', 3: 'warning', 4: 'primary' }
  return typeMap[result] || 'primary'
}

const formatMeasures = (measures: string[]) => {
  const measureMap = {
    reScore: '重新评分',
    reExam: '重新考试',
    changeResult: '更改评价结果',
    compensation: '给予补偿',
    apology: '公开道歉',
    other: '其他措施'
  }
  return measures.map(m => measureMap[m] || m).join('、')
}

const previewFile = (file: any) => {
  // TODO: 实现文件预览
  console.log('预览文件:', file)
}

const submitHandle = async () => {
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    // TODO: 提交处理结果
    console.log('提交异议处理:', handleForm.value)
    dialogVisible.value = false
    emit('success')
    ElMessage.success('异议处理提交成功')
  } finally {
    formLoading.value = false
  }
}

const saveAsDraft = async () => {
  formLoading.value = true
  try {
    // TODO: 保存草稿
    console.log('保存异议处理草稿:', handleForm.value)
    ElMessage.success('草稿保存成功')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  handleForm.value = {
    objectionId: '',
    handleResult: undefined,
    handleMeasures: [],
    rejectReasons: [],
    handleDescription: '',
    handleDeadline: '',
    handler: '当前用户',
    reviewer: '',
    notifyMethods: []
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const open = (data: any) => {
  dialogVisible.value = true
  objectionData.value = data
  handleForm.value.objectionId = data.id
  resetForm()
}

defineExpose({ open })
</script> 